/**
 * 
 * 项目名称：HumanResorceManage
 * 类名称：commonUtils
 * 类描述：读取配置文件信息
 * 创建人：Echo
 * 创建时间：2015年3月12日 下午4:40:31
 * 修改人：Echo
 * 修改时间：2015年3月12日 下午4:40:31
 * 修改备注：
 * @version 
 * 
 */
package com.lst.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.multipart.MultipartFile;

import com.lst.common.CommonEnum;
import com.lst.common.ImgCompress;
import com.lst.model.MstButton;
import com.lst.model.Resources;
import com.lst.model.MstUser;
import com.lst.model.UserRole;
import com.lst.service.MstButtonService;
/**
 * @ClassName: commonUtils
 * @Description: 读取配置文件信息
 * @author Echo
 * @date 2015年3月12日 下午4:40:31
 * 
 */
public class CommonUtils {
	private static Logger logger = Logger.getLogger("log");
	/**
	 * 
	 * @Title: randomFileName
	 * @Description: random File Name
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public static String randomFileName() {
		return Date2String(new Date(), "yyyyMMddHHmmssSSSS");
	}

	/**
	 * 
	 * @Title: Date2String
	 * @Description: Date 2 String
	 * @param @param date
	 * @param @param format
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public static String Date2String(Date date, String format) {
		if (date == null) {
			return "";
		}

		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	/**
	 * 
	 * @Title: readPermissionWithBtn
	 * @Description: 读取用户某菜单按钮权限
	 * @param @param menuId
	 * @param @param mstUser
	 * @param @param mstButtonService
	 * @param @return    设定文件
	 * @return List<MstButton>    返回类型
	 */
	public static List<MstButton> readPermissionWithBtn(int menuId,MstUser mstUser ,MstButtonService mstButtonService){
		Map<String, Object> perMap = new HashMap<String,Object>();
		perMap.put("menuId", menuId);

		perMap.put("alMastertype", CommonEnum.SYSCODE_ROOTBELONG_2);
		perMap.put("alMastervalue",  mstUser.getId());

		perMap.put("rolMastertype", CommonEnum.SYSCODE_ROOTBELONG_3);
		//读取多角色按钮
		List<MstButton> btns = new ArrayList<MstButton>();
		for(UserRole ur : mstUser.getUrs()){
			perMap.put("rolMastervalue", ur.getRolid());
			List<MstButton> tempBtns =  mstButtonService.queryListForUserRoots(perMap);
			if(!tempBtns.isEmpty()){
				btns.addAll(tempBtns);
			}
		}

		//筛选不同角色可能有重叠的按钮权限
		Map<Integer, MstButton> tempMap = new HashMap<Integer,MstButton>();
		for(MstButton btn : btns){
			if(!tempMap.containsKey(btn.getId())){
				tempMap.put(btn.getId(), btn);
			}
		}

		List<MstButton> _btns = new ArrayList<MstButton>();
		Set<Entry<Integer, MstButton>> set = tempMap.entrySet();
		for(Entry<Integer, MstButton> entry: set){
			_btns.add(entry.getValue());
		}

		//排序
		//重写Collections.sort()方法排序方式
		Collections.sort(_btns, new Comparator<MstButton>() {
			public int compare(MstButton arg0, MstButton arg1) {
				return arg0.getTorder().compareTo(arg1.getTorder());
			}
		});

		return _btns;
	}


	/**
	 * 
	 * @Title: saveTempImage
	 * @Description: 保存临时文件
	 * @param @param file
	 * @param @param request
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public static synchronized String saveTempImage(MultipartFile file, HttpServletRequest request) {
		String url = "";

		try {
			String fName = file.getOriginalFilename();
			String suffix = "";

			if (fName.lastIndexOf(".") != -1 && fName.lastIndexOf(".") != 0) {
				suffix = fName.substring(fName.lastIndexOf(".") + 1);
			}

			String realPath = request.getSession().getServletContext().getRealPath("/temp");//项目文件夹

			//String fileName = CommonUtils.randomFileName() + "." + suffix;
			String fileName = "";
			Random random = new Random();
			Integer count = random.nextInt(1000);
			try {
				fileName = DateUtil.getCurrentTime(DateUtil.ALL_DATETIME_STRING_QUEUE_MILL) + "_" + count.toString() + "." + suffix;
			} catch (ParseException e) {
				logger.error("saveTempImage error: " ,e);
			}

			File newFile = new File(realPath + "/" + fileName);
			FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);

			url = fileName;//CommonEnum.RESOURCE_URL_IMAGE +
		} catch (IOException e) {
			logger.error("saveTempImage error: " ,e);
		}

		return url;
	}

	/**
	 * 
	 * @Title: getResourcesData
	 * @Description:读取资源信息
	 * @param @param request
	 * @param @param imagename
	 * @param @param map
	 * @param @return
	 * @param @throws ParseException
	 * @param @throws IOException    设定文件
	 * @return List<MstResources>    返回类型
	 */
	public static Map<String, Object> getResourcesData(HttpServletRequest request , String [] imagename,Map<String, String> map,Integer resType,boolean isZip) throws ParseException, IOException{
		Date startDate = new Date();

		Map<String, Object> resMap = new HashMap<String, Object>();
		List<Resources> resources = new ArrayList<Resources>();
		//路径参数
		//String tempPath  = request.getServletContext().getRealPath("/") + "temp" ;
		String tempPath = request.getServletContext().getRealPath("/") + "\\temp\\" ;

		String resPath = "";
		String filePath = "";
		if(CommonEnum.SYSCODE_REOURCES_TYPE_IMAGE.equals(resType)){
			//filePath = ConfigProp.getImg_file_path();//本地磁盘文件夹
			filePath = ConfigProp.getImg_file_path_linux();//服务器文件夹

			resPath = CommonEnum.RESOURCE_URL_IMAGE;
		} else if(CommonEnum.SYSCODE_REOURCES_TYPE_VIDEO.equals(resType)){
			//filePath = ConfigProp.getVideo_file_path();//本地磁盘文件夹
			filePath = ConfigProp.getVideo_file_path_linux();//服务器文件夹

			resPath = CommonEnum.RESOURCE_URL_VIDEO;
		} else {
			//filePath = ConfigProp.getImg_file_path();//本地磁盘文件夹
			filePath = ConfigProp.getImg_file_path_linux();//服务器文件夹

			resPath = CommonEnum.RESOURCE_URL_IMAGE;
		}

		String newPath = "";

		String currTime = DateUtil.getCurrentTime(DateUtil.ALL_DATE_HORIZONTAL);
		newPath = filePath + currTime;

		//资源参数
		Integer userId = Integer.valueOf(map.get("userId"));
		Integer ownerId = Integer.valueOf(map.get("ownerId"));
		String tableName = map.get("tableName");

		if(imagename != null && imagename.length != 0){
			for(int i = 0;i < imagename.length ;i++){
				if(imagename[i] != null && imagename[i] !=""){
					File tempFile  = new File(tempPath + imagename[i]);
					
					//APP用户图片尺寸设置100px * 100px 
					if("MST_CLIENT".equals(tableName)){
						Image srcImg = ImageIO.read(tempFile);  
						BufferedImage buffImg = null;  
						buffImg = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);  
						buffImg.getGraphics().drawImage(  
								srcImg.getScaledInstance(100, 100, Image.SCALE_SMOOTH), 0,  
								0, null);  
						
						String suffix = "";

						if (imagename[i].lastIndexOf(".") != -1 && imagename[i].lastIndexOf(".") != 0) {
							suffix = imagename[i].substring(imagename[i].lastIndexOf(".") + 1);
						}
						logger.info("decPara imagename["+i+"]:" + imagename[i]);
						logger.info("decPara suffix:" + suffix);
						ImageIO.write(buffImg, suffix,tempFile );  
					} 
					
					File newFile = new File(newPath);

					// 创建当天的文件
					
					if (!newFile.exists()) {
						newFile.mkdirs();
					}

					FileUtils.copyFileToDirectory(tempFile, newFile);

					//创建一份压缩文件
					if(isZip){
						String zipFile = "";
						String abPath = newFile.getAbsolutePath() + "\\" + tempFile.getName();
						ImgCompress  ic = new ImgCompress(abPath);
						zipFile = ic.resize(200, 200);

						zipFile = resPath + currTime + "/" + zipFile;

						resMap.put("zipFile", zipFile);
					}

					String extname = imagename[i].substring(imagename[i].indexOf("."),imagename[i].length());

					Resources resource = new Resources();
					resource.setCreatedate(startDate);
					resource.setCreateuser(userId);
					resource.setEnabled(true);
					resource.setExtname(extname);
					resource.setIsdeleted(false);
					resource.setResname(imagename[i]);
					resource.setRespath(resPath + currTime + "/");
					resource.setOrderindex(i);
					resource.setOwnerid(ownerId);
					resource.setOwnertablename(tableName);
					resource.setRestype(resType);

					resources.add(resource);
				}
			}

		}

		resMap.put("resources", resources);

		return resMap;
	}

	/**
	 * 
	 * @Title: sendSMS
	 * @Description:发送手机短息
	 * @param @param formparams
	 * @param @return    设定文件
	 * @return String    返回类型
	 */
	public static String sendSMS(List<NameValuePair> formparams){
		CloseableHttpClient httpclient = HttpClients.createDefault();  

		// 创建httppost    
		//HttpPost httppost = new HttpPost(CommonEnum.SMS_URL);
		HttpPost httppost = new HttpPost(ConfigProp.getSMS_URL());

		String result = null;

		UrlEncodedFormEntity uefEntity;  
		try {  
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
			httppost.setEntity(uefEntity);  

			System.out.println("executing request " + httppost.getURI());

			CloseableHttpResponse response = httpclient.execute(httppost);  

			try {  
				HttpEntity entity = response.getEntity();  
				if (entity != null) {  
					result = EntityUtils.toString(entity, "UTF-8");

					logger.info("--------------------------------------");  
					logger.info("Response content: " + result);  
					logger.info("--------------------------------------");
				}  
			} finally {  
				response.close();  
			}  
		} catch (ClientProtocolException e) {  
			logger.error("sendSMS error:" ,e);
		} catch (UnsupportedEncodingException e1) {  
			logger.error("sendSMS error:" ,e1);
		} catch (IOException e) {  
			logger.error("sendSMS error:" ,e);
		} finally {  
			// 关闭连接,释放资源    
			try {  
				httpclient.close();  
			} catch (IOException e) {  
				logger.error("sendSMS error:" ,e); 
			}  
		}

		return result;  
	}

	/**
	 * 
	 * @Title: faramsLogForForm
	 * @Description: 输出表单错误日志
	 * @param @param br    设定文件
	 * @return void    返回类型
	 */
	public static void faramsLogForForm(BindingResult br){
		List<ObjectError> ers = br.getAllErrors();
		logger.info("--------------form parameter error start-----------------------");

		for(ObjectError er : ers){
			logger.info("save faile with parameter illegal: " + er.getDefaultMessage() );
		}

		logger.info("--------------form parameter error end-----------------------");
	}

	/**
	 * 
	 * @Title: formatStr
	 * @Description: 格式化字符
	 * @param @param oriStr 原始字符串
	 * @param @param ch     格式化字符
	 * @param @param regex  格式化规则
	 * @param @return    设定文件
	 * @return String    返回类型
	 */
	public static String formatStr(String oriStr,String ch,String regex){

		String newStr = "";
		if(!StringUtils.isEmpty(oriStr)){
			String [] strArr = oriStr.split(regex);

			for(String str : strArr){
				if(!StringUtils.isEmpty(str)){
					newStr += ch + str + regex + "<br/>";
				} else {
					newStr += "<br/>";
				}
			}
		}

		return newStr;
	} 

	/*	public static void main(String[] args) {
		//短息发送
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		String content = String.format("%s|%s|s", "测试1","2016年12月29日15:30-16:30");

		formparams.add(new BasicNameValuePair("userid", "2"));  
		formparams.add(new BasicNameValuePair("receivetype",(CommonEnum.SYSCODE_MSG_RECEIVE_TYPE_CLIENT).toString()));  
		formparams.add(new BasicNameValuePair("mobileno", "18221480269"));  
		formparams.add(new BasicNameValuePair("mirror", "payment")); 
		formparams.add(new BasicNameValuePair("values",content)); 

		String result = CommonUtils.sendSMS(formparams);

	}*/


}